package org.yelongframework.servlet.resource;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.yelongframework.commons.nio.charset.CharsetUtil;
import org.yelongframework.servlet.resource.response.ResourceResponseHandler;
import org.yelongframework.servlet.resource.response.ResourceResponseProperties;
import org.yelongframework.util.Assert;

/**
 * 资源Servlet
 * 
 * @since 1.0.0
 */
public class ResourceServlet extends HttpServlet {

	private static final long serialVersionUID = -8047369128985763547L;

	/** 资源Servlet属性 */
	protected ResourceServletProperties resourceServletProperties;

	/** 资源响应处理器 */
	protected ResourceResponseHandler resourceResponseHandler;

	public ResourceServlet() {
	}

	/**
	 * @param resourceResponseHandler 资源响应处理器
	 */
	public ResourceServlet(ResourceResponseHandler resourceResponseHandler) {
		this(null, resourceResponseHandler);
	}

	/**
	 * @param resourceServletProperties 资源Servlet属性
	 * @param resourceResponseHandler   资源响应处理器
	 */
	public ResourceServlet(ResourceServletProperties resourceServletProperties,
			ResourceResponseHandler resourceResponseHandler) {
		this.resourceResponseHandler = resourceResponseHandler;
		this.resourceServletProperties = resourceServletProperties;
	}

	@Override
	public void init() throws ServletException {
		Assert.notNull(resourceResponseHandler, "resourceResponseHandler cannot be null");
		if (null == resourceServletProperties) {
			resourceServletProperties = new ResourceServletProperties();
		}
	}

	@Override
	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String encoding = resourceServletProperties.getEncoding();
		// 默认编码UTF-8
		if (StringUtils.isBlank(encoding)) {
			encoding = CharsetUtil.UTF_8_STRING;
		}
		response.setCharacterEncoding(encoding);
		ResourceResponseProperties resourceResponseProperties = new ResourceResponseProperties(request, response);
		// 资源响应处理
		resourceResponseHandler.handle(resourceResponseProperties);
	}

	/**
	 * @return 资源Servlet属性
	 */
	public ResourceServletProperties getResourceServletProperties() {
		return resourceServletProperties;
	}

	/**
	 * @param resourceServletProperties 资源Servlet属性
	 */
	public void setResourceServletProperties(ResourceServletProperties resourceServletProperties) {
		this.resourceServletProperties = resourceServletProperties;
	}

	/***
	 * @return 资源响应处理器
	 */
	public ResourceResponseHandler getResourceResponseHandler() {
		return resourceResponseHandler;
	}

	/**
	 * @param resourceResponseHandler 资源响应处理器
	 */
	public void setResourceResponseHandler(ResourceResponseHandler resourceResponseHandler) {
		this.resourceResponseHandler = resourceResponseHandler;
	}

}
